package com.task.mall.dao.impl;

import com.task.mall.bean.Goods;
import com.task.mall.bean.Type;
import com.task.mall.dao.TypeDao;
import com.task.mall.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class TypeDaoImpl implements TypeDao {
    QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());

    @Override
    public List<Type> getType() {
        List<Type> typeList = null;
        try {
            typeList = runner.query("select * from type",
                    new BeanListHandler<>(Type.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return typeList;
    }

    @Override
    public int addType(Type type) {
        int update = 0;
        try {
            update = runner.update("insert into type values (null, ?)",
                    type.getName());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (update != 0) {
            return 200;
        }
        return 10000;
    }

    @Override
    public int deleteType(int typeId) {
        try {
            runner.update("delete from type where id = ?",typeId);
            return 200;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 10000;
    }

    @Override
    public List<Goods> getGoodsByType(String typeId) {
        List<Goods> goodsList = null;
        if (!"-1".equals(typeId)){
            try {
                goodsList = runner.query("select * from goods where typeId = ?",
                        new BeanListHandler<>(Goods.class),
                        typeId);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }  else{
            try {
                goodsList = runner.query("select * from goods",
                        new BeanListHandler<>(Goods.class));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return goodsList;
    }

    /**
     * 根据关键字搜索相关商品
     * @param keyword
     * @return
     */
    @Override
    public List<Goods> searchGoods(String keyword) {
        List<Goods> goodsList = null;
        try {
            goodsList = runner.query("select * from goods where name like ?",
                    new BeanListHandler<>(Goods.class),
                    "%" + keyword + "%");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return goodsList;
    }
}
